package com.wsc.personalblog.controller;

import com.wsc.personalblog.DTO.RoleDTO;
import com.wsc.personalblog.DTO.UserDTO;
import com.wsc.personalblog.service.RoleService;
import com.wsc.personalblog.utils.AliYunOssUtil;
import com.wsc.personalblog.common.Constant;
import com.wsc.personalblog.common.Result;
import com.wsc.personalblog.entity.User;
import com.wsc.personalblog.security.SecurityUser;
import com.wsc.personalblog.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api("用户相关的操作")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String , Object> redisTemplate;

    /**
     * 验证是否登录，jwt认证过滤器就可以解决，该方法只需要返回一个无参success
     * @return
     */
    @PreAuthorize("hasRole('BOSS')")
    @PostMapping("/checkLogin")
    public Result<String> checkLogin(){
        log.info("验证成功");
        return Result.successNoData();
    }

    /**
     * 忘记密码时修改密码
     * @return
     */
    @PostMapping("/forgetPassword")
    public Result<String> forgetPassword(@RequestBody Map<String,Object> map) throws IOException {
        String newPassword = (String)map.get("newPassword");
        String mail = (String)map.get("mail");
        String code = (String)map.get("code");
        userService.forgetPassword(newPassword,mail,code);
        return Result.successNoData();
    }

    /**
     * 修改密码
     * @return
     */
    @PostMapping("/updatePassword")
    public Result<String> updatePassword(@RequestBody Map<String,Object> map) throws IOException {
        String newPassword = (String)map.get("newPassword");
        String oldPassword = (String)map.get("oldPassword");
        userService.updatePassword(newPassword,oldPassword);
        return Result.successNoData();
    }

    /**
     * 修改用户名
     * @return
     */
    @PostMapping("/updateUsername")
    public Result<String> updateUsername(@RequestBody Map<String,Object> map) throws IOException {
        String username = (String)map.get("username");
        userService.updateUsername(username);
        return Result.successNoData();
    }

    /**
     * 修改头像
     * @return
     */
    @PostMapping("/updateAvatar")
    public Result<String> updateAvatar(@RequestPart("avatar") MultipartFile avatar) throws IOException {
        String fileName = userService.updateAvatar(avatar);
        return Result.successHaveData(fileName);
    }

    /**
     * 获取注册时验证码
     * @return
     */
    @PostMapping("/public/sendCode")
    public Result<String> getVerificationCode(@RequestBody Map<String,Object> mail){
        String mail1 = (String)mail.get("mail");
        userService.getVerificationCode(mail1);
        return Result.successNoData();
    }

    /**
     * 获取登录时验证码
     * @return
     */
    @PostMapping("/public/login/sendCode")
    public Result<String> getLoginVerificationCode(@RequestBody Map<String,Object> mail){
        String mail1 = (String)mail.get("mail");
        userService.getLoginVerificationCode(mail1);
        return Result.successNoData();
    }
    /**
     * 获取找回密码时的验证码
     * @return
     */
    @PostMapping("/forget/sendCode")
    public Result<String> getForgetVerificationCode(@RequestBody Map<String,Object> mail){
        String mail1 = (String)mail.get("mail");
        userService.getForgetVerificationCode(mail1);
        return Result.successNoData();
    }

    /**
     * 后台系统邮箱验证码登录
     * 登入成功返回token
     * @param user
     * @return
     */
    @PostMapping("/public/backendEmailLogin")
    public Result<UserDTO> backendEmailLogin(@RequestBody UserDTO user){
        UserDTO userDTO = userService.backendEmailLogin(user);
        return Result.successHaveData(userDTO);
    }

    /**
     * 邮箱验证码登录方式
     * @return
     */
    @PostMapping("/public/emailLogin")
    public Result<UserDTO> emailLogin(@RequestBody UserDTO user){
        UserDTO userDTO = userService.emailLogin(user);
        return Result.successHaveData(userDTO);
    }

    /**
     * 登入成功返回token
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result<UserDTO> login(@RequestBody User user){
        log.info(user.getUsername()+"请求登录"+"携带密码："+user.getPassword());
        UserDTO res = userService.login(user);
        return Result.successHaveData(res);
    }

    /**
     * 后台系统登录
     * 登入成功返回token
     * @param user
     * @return
     */
    @PostMapping("/backendLogin")
    public Result<UserDTO> backendLogin(@RequestBody User user){
        log.info(user.getUsername()+"请求登录"+"携带密码："+user.getPassword());
        UserDTO res = userService.backendLogin(user);
        return Result.successHaveData(res);
    }

    /**
     * 自动登录
     * @return
     */
    @PostMapping("/public/autoLogin")
    public Result<UserDTO> autoLogin(HttpServletRequest request){
        String token = request.getHeader("token");
        UserDTO userDTO = userService.autoLogin(token);
        return Result.successHaveData(userDTO);
    }

    /**
     * 后台自动登录
     * @return
     */
    @PostMapping("/public/backendAutoLogin")
    public Result<UserDTO> backendAutoLogin(HttpServletRequest request){
        String token = request.getHeader("token");
        UserDTO userDTO = userService.backendAutoLogin(token);
        return Result.successHaveData(userDTO);
    }

    @PostMapping("/logout")
    public Result<String> logout(){
        // 拿到用户信息，删除redis中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        Integer userid = securityUser.getUser().getId();
        redisTemplate.delete(Constant.LOGIN+userid) ;
        return Result.successNoData();
    }
    @PreAuthorize("hasRole('BOSS')")
    @PostMapping("/backendLogout")
    public Result<String> backendLogout(){
        // 拿到用户信息，删除redis中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        Integer userid = securityUser.getUser().getId();
        redisTemplate.delete(Constant.BOSS_LOGIN+userid) ;
        return Result.successNoData();
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody UserDTO user){
        userService.register(user);
        return Result.successNoData();
    }

    @PostMapping("/public/avatarUpload")
    public Result<String> avatarUpload(@RequestPart("avatar") MultipartFile avatar) throws IOException {
        UUID uuid = UUID.randomUUID();
        String fileName = uuid.toString();
        if(avatar != null){
            if(!avatar.isEmpty()){
                String originalFilename = avatar.getOriginalFilename();
                String[] split = originalFilename.split("\\.");
                fileName = fileName+"."+split[1];
                // 上传到阿里云OSS
                AliYunOssUtil.upload(avatar.getBytes(), fileName);
            }
        }
        return Result.successHaveData(fileName);
    }
    @DeleteMapping("/public/avatar")
    @ApiOperation("图片删除")
    public Result<String> deletePhoto(
            @RequestParam("fileName") String fileName
    )  {
        AliYunOssUtil.DeleteOne(fileName);
        return Result.successNoData();
    }

    @GetMapping
    @PreAuthorize("hasRole('admin')")
    public Result<List<User>> getUserInfoList() {
        List<User> userList = userService.getUserInfoList();
        return Result.successHaveData(userList);
    }

    @GetMapping("/{name}")
    @PreAuthorize("hasRole('admin')")
    public Result<List<User>> getUserInfoListByName(@PathVariable("name") String name) {
        List<User> userList = userService.getUserInfoListByName(name);
        return Result.successHaveData(userList);
    }

    @PostMapping("/add")
    @PreAuthorize("hasRole('BOSS')")
    public Result<Integer> addUser(@RequestBody User user) {
        Integer id = userService.addUser(user);
        return Result.successHaveData(id);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('BOSS')")
    public Result<String> removeUser(@PathVariable("id") Integer id) {
        userService.removeUser(id);
        return Result.successNoData();
    }
    @PutMapping()
    @PreAuthorize("hasRole('BOSS')")
    public Result<String> updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return Result.successNoData();
    }

    @GetMapping("/role")
    @PreAuthorize("hasRole('BOSS')")
    public Result<RoleDTO> getRole(@RequestParam Integer userId) {
        RoleDTO roleDTO = userService.getRole(userId);
        return Result.successHaveData(roleDTO);
    }

    @PutMapping("/role")
    @PreAuthorize("hasRole('BOSS')")
    public Result<String> updateRole(@RequestBody RoleDTO roleDTO) {
        userService.updateRole(roleDTO);
        return Result.successNoData();
    }


}
